import redis

from test_queue import MysqlDb


class Client:
    def __init__(self):
        self.r = redis.Redis(decode_responses=True)
        self.key = 'server'

    # 入列
    def push(self, uid, msg):
        self.r.hset(self.key, uid, msg)

    # 出列
    def out(self, cid, sid):
        mydb = MysqlDb()
        mydb.update("update `muser` set clientid=%s where id=%s" % (sid, cid))
        mydb.update("update `muser` set serverid=%s where id=%s" % (cid, sid))
        self.r.hdel(self.key, cid)

    # 查看全部
    def getall(self):
        return self.r.hgetall(self.key)

    def get(self, id):
        return self.r.hget(self.key, id)


# cl=Client()
# print(cl.get(4))
# cl.push(4,'你好')
# cl.out(4)
# print(cl.getall())

# 连天记录 储存和查看
class MChat:
    def __init__(self):
        self.r = redis.Redis(decode_responses=True)

    def push(self, key, msg):
        if self.r.exists(key):
            self.r.lpush(key, msg)
        else:
            self.r.lpush(key, msg)
            self.r.expire(key, 120)

    def get(self, key):
        return self.r.lrange(key, 0, -1)
